<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Dao;

use App\Kernel\Traits\DaoTrait;
use App\Model\Goods;

/**
 * 商品 DAO
 *
 * @author 谢声强(861167322@qq.com)
 * @package App\Dao
 */
class GoodsDao extends Dao
{
    use DaoTrait;

    /**
     * 通过分类 ID 获取商品列表
     *
     * @param array $map
     * @param int $page_size
     * @return mixed
     */
    public function getGoodsListByCategory(array $map)
    {
        return  Goods::query()
            ->select('id', 'title', 'price', 'original_price', 'stock', 'picture','category_id')
            ->where(function ($query) use ($map) {
                return queryWhere($query, $map);
            })
            ->get();
    }

    /**
     * 检查商品是否存在
     * @param int $id
     * @return bool
     */
    public function checkExistById(int $id)
    {
        return Goods::query()->where('id', $id)->exists();
    }

    /**
     * 根据商品标题搜索
     *
     * @author 刘兴永(aile8880@qq.com)
     * @date 2020-02-22 19:57:00
     * @param string $goods_title 商品标题
     * @param array $sort_rule 排序规则
     * @param array $price_range 价格区间
     * @param integer $page_size 分页数量
     * @return mixed
     */
    public function search(string $goods_title, array $sort_rule = [], $price_range = [], int $page_size = 12)
    {
        $model = Goods::query()->select('id', 'title', 'price', 'picture','original_price', 'stock');

        // 设置商品标题
        if (! empty($goods_title)) {
            $model->where('title', 'like', "%{$goods_title}%");
        }

        // 设置价格区间
        if (! empty($price_range)) {
            $model->whereBetween('price', $price_range);
        }

        // 设置排序
        if (! empty($sort_rule)) {
            $model->orderBy($sort_rule[0], $sort_rule[1]);
        }

        return $model->paginate($page_size);
    }

    /**
     * 通过分类 ID 获取商品列表
     *
     * @param array $map
     * @param int $page_size
     * @return mixed
     */
    public function getGoodsListByCategorySuper(array $map, int $page_size = 12)
    {
        return  Goods::query()
            ->select('id', 'title', 'price', 'original_price', 'stock', 'picture')
            ->where(function ($query) use ($map) {
                return queryWhere($query, $map);
            })
            ->orderBy('sort', 'desc')
            ->orderBy('id', 'desc')
            ->paginate($page_size);
    }

    /**
     * 通过分类 ID 获取商品列表
     *
     * @param int $category_id
     * @param int $page_size
     * @return mixed
     */
    public function getGoodsListByCategoryId(int $category_id, int $page_size = 12)
    {
        return empty($category_id) ? Goods::query()
            ->select('id', 'title', 'price', 'original_price', 'stock', 'picture')
            ->where('is_marketable', 1)
            ->where('disable', 1)
            ->orderBy('sort', 'desc')
            ->orderBy('id', 'desc')
            ->paginate($page_size): Goods::query()
            ->select('id', 'title', 'price', 'original_price', 'stock', 'picture')
            ->where('category_id', $category_id)
            ->where('is_marketable', 1)
            ->where('disable', 1)
            ->orderBy('sort', 'desc')
            ->orderBy('id', 'desc')
            ->paginate($page_size);
    }

    /**
     * 通过商品ID获取商品信息
     *
     * @author 刘兴永(aile8880@qq.com)
     * @date 2020-02-22 19:57:00
     * @param int $goods_id
     * @param bool $abnormal
     * @return mixed
     */
    public function first(int $goods_id, bool $abnormal = true)
    {
        $first = Goods::query()
            ->with('contents')
            ->with('sku')
            ->where('id', $goods_id)
            ->first();

        if (!$first && $abnormal === true) {
            $this->error('GOODS.NOT_FOUND');
        }

        return $first;
    }

    /**
     * 通过商品ID查询商品
     * @param int $id
     * @return mixed
     */
    public function getGoodsById(int $id)
    {
        $first = Goods::query()
            ->where('id', $id)
            ->first();

        if (!$first) {
            $this->error('GOODS.NOT_FOUND');
        }

        return $first;
    }

    /**
     * 通过商品ID select查询商品
     * @param int $id
     * @param array|null $select
     * @return mixed
     */
    public function getGoodsSelectById(int $id, array $select = null)
    {
        $first = Goods::query()
            ->where('id', $id);
        $select !== null && $first = $first->select($select);

        $first = $first ->first();

        if (!$first) {
            $this->error('GOODS.NOT_FOUND');
        }

        return $first;
    }

    /**
     * 通过商品ID判断商品是否存在
     *
     * @author 刘兴永(aile8880@qq.com)
     * @date 2020-02-22 19:57:00
     *
     * @param int $id
     * @return bool
     */
    public function existsGoodsById(int $id)
    {
        if ($id === 0) return false;

        return Goods::query()->where('id', $id)->exists();
    }

    /**
     * 通过条件查询商品
     *
     * @param array $map
     * @return mixed
     */
    public function get(array $map = [])
    {
        return Goods::query()
            ->where(function ($query) use ($map) {
                return queryWhere($query, $map);
            })
            ->orderByDesc('sort')
            ->orderBy('id')
            ->select('picture', 'title', 'price', 'integral')
            ->paginate(10);
    }

    /**
     * 减库存
     *
     * @param int $id
     * @param int $num
     * @return int
     */
    public function decreaseStock(int $id, int $num)
    {
        if ($num <= 0) $this->error();

        return Goods::query()->where('id', $id)->where('stock', '>=', $num)->decrement('stock', $num);

    }

    /**
     * 加库存
     *
     * @param int $id
     * @param int $num
     * @return int
     */
    public function addStock(int $id, int $num)
    {
        if ($num <= 0) $this->error();

        return Goods::query()->where('id', $id)->increment('stock', $num);
    }

    /**
     * 获取商品通过map
     * @param array $map
     * @param string|null $sort
     * @param array|null $select
     * @param int|null $paginate
     * @return mixed
     */
    public function getGoodsByMap(array $map = [], string $sort = null, array $select = null, int $paginate = null)
    {
        $model = self::makeModel();

        if (isset($map['between_field'])) {
            foreach ($map['between_field'] as $k => $value) {
                $model = $model->whereBetween($k, $value);
            }
            unset($map['between_field']);
        }

        if (!empty($map)) {
            $model = $model->where(function ($query) use ($map) {
                return queryWhere($query, $map);
            });
        }
        if (null !== $sort) {
            $model = $model->orderByRaw($sort);
        }

        if (null !== $select) {
            $model = $model->select($select);
        }

        return $paginate > 0 ? $model->paginate($paginate) : $model->get();

    }

    /**
     * 创建商品返回商品ID
     * @param array $data
     * @return int
     */
    public function createGetId(array $data)
    {
        return Goods::query()->insertGetId($data);
    }

    /**
     * Get model.
     *
     * @return string
     */
    public function model(): string
    {
        return Goods::class;
    }
}